#!/bin/bash
# export LC_ALL=en_US.UTF-8  # 强制使用UTF-8编码环境

workspace=$(pwd)

num_addition="" #附加字符
num_character="1234567890 .:%/"
english_chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
engilsh_character="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+-=[]{}|;:,.<>?/\\'\""
chinese_character="\"。，？！；：、（）【】“”‘’"
chinese_3500_character="${workspace}/tools/font_array/chinese_3500.txt"
international_commonly_used_character="${workspace}/tools/font_array/chars.txt"

default_font_bpp=4
other_sizes=(40 48 70 125)

csv_file="${workspace}/tools/language/translations/all_characters.csv"
# csv_file="tools/language/translations/non_ascii_characters.csv"
font_dir="${workspace}/tools/font_array"
output_dir="${workspace}/components/applications/apps-projector/source/hcprojector_app/guider/custom/fonts"

# 检查文件编码是否为UTF-8
check_encoding() {
    file_encoding=$(file -bi "$1" | awk -F'=' '{print $2}')
    [ "$file_encoding" != "utf-8" ] && {
        echo "错误: CSV文件编码需要UTF-8，检测到 $file_encoding"
        exit 1
    }
}

# 修复字符分割逻辑
split_chars() {
    python3 -c "
import sys
for line in sys.stdin:
    print('\n'.join(sorted(set(line.strip()), key=lambda x: ord(x))))
"
}

process_row() {
    local size=$1
    local weight=$2
    local chars=$3

    # 选择对应字体文件
    case "$weight" in
    bold) font_file="${font_dir}/SourceHanSansSC-Bold.otf" ;;
    regular) font_file="${font_dir}/SourceHanSerifSC-Regular.otf" ;;
    *)
        echo "跳过未知字重: $weight"
        return
        ;;
    esac

    [ ! -f "$font_file" ] && {
        echo "错误: 字体文件不存在 $font_file"
        return
    }

    # 创建UTF-8编码的临时文件
    tmp_chars=$(mktemp)
    #   echo "$chars" > "$tmp_chars"
    echo "$chars$num_character" >"$tmp_chars"
    iconv -f UTF-8 -t UTF-8//IGNORE "$tmp_chars" -o "$tmp_chars" # 清理无效字节

    # 生成文件名
    font_name=$(basename "$font_file" .otf | tr '[:upper:]' '[:lower:]' | tr -d '-')
    output_file="${output_dir}/font_${font_name}_${size}_${default_font_bpp}bpp.c"

    # 执行生成命令
    if python3 ${font_dir}/mkfont_array.py \
        --fontfile "$font_file" \
        --charset "$tmp_chars" \
        --size "$size" \
        --bpp ${default_font_bpp} \
        --output_dir "$output_dir"; then
        echo "成功生成: ${output_file}"
    else
        echo "生成失败: ${output_file}"
    fi

    rm "$tmp_chars"
}

# 主流程
check_encoding "$csv_file"

if [ -e $output_dir ]; then
    rm -rf $output_dir
    mkdir -p $output_dir
else
    mkdir -p $output_dir
fi

awk '
BEGIN {
    FPAT = "([^,]*)|(\"[^\"]+\")"  # 识别带引号的字段
}
NR > 1 {
    # 直接提取处理后的字段
    size = $1
    weight = $2
    chars = $3

    # 输出处理结果
    print size, weight, chars
}' "$csv_file" | while IFS=, read -r size weight chars; do
    # 直接传递已清理的字符（假设 chars 列已唯一）
    # echo "Processing: $size, $weight, $chars"

    #! regular 20 的字体添加额外的数据
    if [ $size -eq 20 ] && [ $weight = "regular" ]; then
        chars+=$english_chars$num_character$num_addition
    fi
    if [ $size -eq 18 ] && [ $weight = "bold" ]; then
        chars+=$english_chars$num_character$num_addition
    fi

    # if [ $size -eq 32 ] && [ $weight = "regular" ]; then
    #     continue  # 跳过本次循环的后续代码（包括 process_row）
    # fi

    # if [ $size -eq 24 ] && [ $weight = "regular" ]; then
    #     continue  # 跳过本次循环的后续代码（包括 process_row）
    # fi
    process_row "$size" "$weight" "$chars"
done

num_charset=$(mktemp)
echo "$num_character" >"$num_charset"

echo "生成 其他仅包含数字的字体文件！"

# 循环生成每个尺寸
for size in "${other_sizes[@]}"; do
    echo "正在生成 ${size}px 字体..."
    if python3 ${font_dir}/mkfont_array.py \
        --fontfile ${font_dir}/SourceHanSansSC-Bold.otf \
        --charset "$num_charset" \
        --size "$size" \
        --bpp 4 \
        --output_dir "$output_dir"; then
        echo "成功生成: ${output_dir}/size_${size}"
    else
        echo "生成失败: size=${size}"
    fi
done

echo "生成国际常用文字"

if python3 ${font_dir}/mkfont_array.py \
    --fontfile ${font_dir}/SourceHanSansSC-Bold.otf \
    --charset "$international_commonly_used_character" \
    --size 32 \
    --bpp 2 \
    --output_dir "$output_dir"; then
    echo "成功生成: ${output_dir}/ ${international_commonly_used_character}"
else
    echo "生成失败: 生成国际常用文字"
fi

# if python3 ${font_dir}/mkfont_array.py \
#     --fontfile ${font_dir}/SourceHanSansSC-Bold.otf \
#     --charset "$international_commonly_used_character" \
#     --size 20 \
#     --bpp 4 \
#     --output_dir "$output_dir"; then
#     echo "成功生成: ${output_dir}/ ${international_commonly_used_character}"
# else
#     echo "生成失败: 生成国际常用文字"
# fi

if python3 ${font_dir}/mkfont_array.py \
    --fontfile ${font_dir}/SourceHanSerifSC-Regular.otf \
    --charset "$international_commonly_used_character" \
    --size 24 \
    --bpp 4 \
    --output_dir "$output_dir"; then
    echo "成功生成: ${output_dir}/ ${international_commonly_used_character}"
else
    echo "生成失败: 生成国际常用文字"
fi

echo "处理完成，请检查输出目录: $output_dir"
